package hackathon.att.atl.android.autoresponder;

import hackathon.att.atl.android.autoresponder.GeoLocation.GetLocationFromPhone;
import hackathon.att.atl.android.autoresponder.GeoLocation.Locator;
import hackathon.att.atl.android.autoresponder.SMS.SendSMS;
import hackathon.att.atl.android.autoresponder.SMS.SendSMSFromPhone;
import android.content.Context;

public class SendMessage {
	private static final int MAX_MESSAGE_LENGTH = 150;
	Locator locator;
	SendSMS sendSMS;
	
	public SendMessage(){
		//set default
		sendSMS = new SendSMSFromPhone();
	}
	
	public void sendMessage(Context context, int id){
		String message = "";
		String destinationPhoneNumber = "";
		boolean getLocation = true;
		
		/*From DAO:
		  get message(s) 
		  get destination
		  get boolean*/
		AutoResponderDAO dao = new AutoResponderDAO(context);
		dao.open();
		AutoResponderData data = dao.getContactInfo(id);
		dao.close();
		
		message = data.getText_msg();
		destinationPhoneNumber = data.getPhoneNumber();
		getLocation = data.isGetLocationFlag();
		
		if(getLocation){
			if (locator == null) locator = new GetLocationFromPhone(context);
			message = concatenateLocation(message);
		}

		sendSMS.sendSMS(message, destinationPhoneNumber);
	}

	public SendMessage setLocator(Locator locator){ 
		this.locator = locator;
		return this;
	}
	
	public SendMessage setSendSMS(SendSMS sms){
		this.sendSMS = sms;
		return this;
	}
	
	private String concatenateLocation(String message){
		String location = locator.getLocation();
		
		int lengthToTrim = MAX_MESSAGE_LENGTH - (message.length() + location.length());
		
		String finalMessage = (lengthToTrim > 0) ? message.substring(0, message.length() - lengthToTrim) : message;
		
		finalMessage += location;
				
		return finalMessage;
	}
}
